package cn.snailhd.admin.novel.service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.snailhd.admin.novel.domain.CrawlerNovel;
import cn.snailhd.admin.novel.domain.NovelChapter;
import cn.snailhd.core.base.dao.MyBatisDao;
import cn.snailhd.core.base.domain.PageVo;
import cn.snailhd.utils.string.StringUtils;

@Service
public class NovelService {
	
	@Autowired
	MyBatisDao dao;
	
	public CrawlerNovel queryNovelById(String id) {
		return dao.selectOne("novel.queryNovelById", id);
	};
	
	public PageVo<CrawlerNovel> queryNovelList(Map params){
		PageVo.mathIndex(params);
		return dao.selectForPcPage("novel.queryNovelList",params);
	}

	
	public List<NovelChapter> queryChapters(JSONObject params){
		LinkedList<NovelChapter> queue = new LinkedList<NovelChapter>();

		List<NovelChapter> list = dao.selectList("novel.queryChapters",params);
		Map<String,NovelChapter> map = new HashMap<>();
		if(list == null || list.size()==0){
			return queue;
		}


		for(NovelChapter chapter : list){
			String urlCur = chapter.getUrl_cur();
			map.put(urlCur,chapter);
		}
		NovelChapter curChapter = list.get(0);
		queue.offer(curChapter);
		while (true){
			String urlPre = curChapter.getUrl_pre();
			NovelChapter chapterPre = map.get(urlPre);
			if(chapterPre==null){
				break;
			}
			queue.offer(chapterPre);
			curChapter = chapterPre;
		}
		curChapter = list.get(0);
		while (true){
			String urlNext = curChapter.getUrl_next();
			NovelChapter chapterNext = map.get(urlNext);
			if(chapterNext==null){
				break;
			}
			queue.offerFirst(chapterNext);
            curChapter = chapterNext;
		}

		return queue;
	}


	public void download(OutputStream os,String id) throws IOException {
        JSONObject params = new JSONObject();
        params.put("novelid",id);
        params.put("size",100);
        int index =-100;
    }

	public int updateNovel(CrawlerNovel cra) {
		return dao.update("novel.updateNovel", cra);
	}

	public int addNovel(CrawlerNovel cra) {
		if(StringUtils.isBlank(cra.getId())) cra.setId(StringUtils.guid18());
		return dao.insert("novel.addNovel", cra);
	}

	public int addChapter(CrawlerNovel cra) {
		if(StringUtils.isBlank(cra.getChapterid())) cra.setChapterid(StringUtils.guid18());
		return dao.insert("novel.addChapter", cra);
	}

	public int delNovel(JSONArray list) {
		return dao.delete("novel.delNovel", list);
	}
}
